import { NgModule } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { NavigationEnd, Router, RouteReuseStrategy, RouterModule, Routes } from '@angular/router';
import { AppUiCustomizationService } from '@shared/common/ui/app-ui-customization.service';
import { AppConsts } from './shared/AppConsts';
import { CustomReuseStrategy } from './shared/common/nav/custom-reuse-strategy';

const routes: Routes = [
    { path: '', redirectTo: '/app/main/dashboard', pathMatch: 'full' },
    {
        path: 'account',
        loadChildren: () => import('account/account.module').then(m => m.AccountModule), //Lazy load account module
        data: { preload: true }
    },
    { path: '**', redirectTo: '/app/main/dashboard' }
];

@NgModule({
    imports: [RouterModule.forRoot(routes,
        {
            useHash: true,
            onSameUrlNavigation: 'reload'
        }
    )],
    exports: [RouterModule],
    providers: [
        // { provide: APP_BASE_HREF, useValue: AppConsts.publicBase },
        { provide: RouteReuseStrategy, useClass: CustomReuseStrategy }
    ]
})
export class RootRoutingModule {
    constructor(
        private router: Router,
        private _uiCustomizationService: AppUiCustomizationService) {
        router.events.subscribe((event: NavigationEnd) => {
            setTimeout(() => {
                this.toggleBodyCssClass(event.url);
            }, 0);
        });
    }

    toggleBodyCssClass(url: string): void {
        if (url) {
            if (url === '/') {
                if (abp.session.userId > 0) {
                    this.setAppModuleBodyClassInternal();
                } else {
                    this.setAccountModuleBodyClassInternal();
                }
            }

            if (url.indexOf('/account/') >= 0) {
                this.setAccountModuleBodyClassInternal();
            } else {
                this.setAppModuleBodyClassInternal();
            }
        }
    }

    setAppModuleBodyClassInternal(): void {
        var a = document.getElementsByTagName("app-root")[0];
        let currentBodyClass = a.className;
        a.className = this._uiCustomizationService.copyAppModuleBodyClass(currentBodyClass);
    }

    setAccountModuleBodyClassInternal(): void {
        let currentBodyClass = document.body.className;

        document.body.className = this._uiCustomizationService.copyAccountModuleBodyClass(currentBodyClass);
    }

    getSetting(key: string): string {
        return abp.setting.get(key);
    }
}
